/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ehsunbehravesh.service.security.ejb.password;

import com.ehsunbehravesh.mypasswords.PasswordAnalyser;
import java.util.List;
import java.util.Random;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 *
 * @author ehsun7b
 */
@Stateless(name = "PasswordEJB")
@Local(PasswordLocalBusiness.class)
@Remote(PasswordRemoteBusiness.class)
public class PasswordBean implements PasswordLocalBusiness, PasswordRemoteBusiness {

  private static final String ALPHABETS = "abcdefghijklmnopqrstuvwxyz";
  private static final String CAPITAL_ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private static final String NUMBERS = "0123456789";
  private static final String SPECIAL_CHARS = "_+=-?!@#$%^&*";
  
  @Override
  public String generatePassword(List<CharacterSet> characterSets, int minLength, int maxLength) {
    Random random = new Random(System.currentTimeMillis());
    StringBuilder result = new StringBuilder();
    StringBuilder chars = new StringBuilder();
    
    if (characterSets.contains(CharacterSet.ALPHABETS)) {
      chars.append(ALPHABETS);
    }
    if (characterSets.contains(CharacterSet.CAPITAL_ALPHABETS)) {
      chars.append(CAPITAL_ALPHABETS);
    }
    if (characterSets.contains(CharacterSet.NUMBERS)) {
      chars.append(NUMBERS);
    }
    if (characterSets.contains(CharacterSet.SPECIAL_CHARS)) {
      chars.append(SPECIAL_CHARS);
    }
    
    int charsLength = chars.length();
    
    int passwordLength;
    
    if (minLength == maxLength) {
      passwordLength = minLength;
    } else {
      passwordLength = random.nextInt(maxLength - minLength + 1) + minLength;
    }
    
    for (int i = 0; i < passwordLength; i++) {
      char charAt = chars.charAt(random.nextInt(charsLength));
      result.append(charAt);
    }
    
    return result.toString();
  }

  @Override
  public int passwordMeter(String password) {
    PasswordAnalyser analyser = new PasswordAnalyser(password);
    return analyser.getPoints();
  }
  
}
